const router = require("express")();
const dm = require("../core/DataManager");
const um = require("../core/UserManager");
const fm = require("../core/FileManager");
const crypto = require("crypto");

const img_see1_arr = [0, 1, 3, 4];
const img_see2_arr = [0, 1, 2, 3, 4, 5, 6]
const img_see1 = new Set(img_see1_arr);
const img_see2 = new Set(img_see2_arr);


const ciprl = NCUTCAT.localProperty.catImg_page_record_limit;
router.get("/cat-rand", um.middle_finder, um.middle_loadUser, (req, res) => {
    let query = req.query || {};
    let cid = query.cid,
        uid = query.uid,
        limit = !query.limit || isNaN(query.limit) ? ciprl : Math.min(query.limit, ciprl),
        status = um.permissionCheck(true, req.user, 'see_private_cat_img') ? img_see2_arr : img_see1_arr;

    dm.getCatImgsRandom(cid, uid, limit, status, (err, result) => {
        if (err) return res.json(RES_CHECKER({ success: false, error: err }));

        let data = [];
        for (let info in result) {
            info = result[info];
            let uuid = NCUTCAT.tools.BufferToHex(info.q);
            if (uuid != '0x0') data.push({ hash: uuid, lore: info.u });
        }
        res.json(RES_CHECKER({ success: true, result: data }));

    });
});
/**
 * 获取指定UUID的图片
 * @param uuid 图片UUID
 */
router.get("/cat/:uuid", um.middle_finder, um.middle_loadUser, (req, res) => {
    let uuid = (req.params || {}).uuid;
    if (!uuid) return res.redirect('/public/img/cat/404.jpg');
    dm.getCatImg(uuid, (err, info) => {
        if (!info) return res.redirect('/public/img/cat/404.jpg') && false;
        if (img_see1.has(info.ax) ||
            (um.permissionCheck(true, req.user, 'see_private_cat_img') && img_see2.has(info.ax))) {
            if (req.headers['if-none-match'] == info.ax) return res.status(304).end() && false;
        } else return res.redirect('/public/img/cat/403.jpg') && false;
        return true;
    }, (err, result, info) => {
        res.writeHead(200, {
            'Content-Type': `image/${info.v}`,
            'ETag': info.ax,
            'x-img-pid': info.p,
            'x-img-uuid': NCUTCAT.tools.BufferToHex(info.q),
            'x-img-uid': info.r,
            'x-img-cid': info.s,
            'x-img-description': info.u,
            'x-img-examine': info.ax
        });
        res.write(result.t);
        res.end();
    });
});
/**
 * 获取指定UUID的图片
 * @param uuid 图片UUID
 */
router.get("/thread/:uuid", um.middle_finder, um.middle_loadUser, (req, res) => {
    let uuid = (req.params || {}).uuid;
    if (!uuid) return res.redirect('/public/img/thread/404.jpg');
    let Etag;
    dm.getThreadImg(uuid, (err, info) => {
        if (!info) return res.redirect('/public/img/thread/404.jpg') && false;
        if (img_see1.has(info.status) ||
            (um.permissionCheck(true, req.user, 'see_private_thread_img') && img_see2.has(info.status))) {
            Etag = `${info.tid}-${info.status}`;
            if (req.headers['if-none-match'] == Etag) return res.status(304).end() && false;
        } else return res.redirect('/public/img/thread/403.jpg') && false;
        return true;
    }, (err, result, info) => {
        res.writeHead(200, {
            'Content-Type': `image/${result.type}`,
            'ETag': Etag,
            'x-img-tid': info.tid,
            'x-img-uuid': NCUTCAT.tools.BufferToHex(info.pid),
            'x-img-uid': info.uid,
            'x-img-description': result.lore,
            'x-img-examine': info.status
        });
        res.write(result.data);
        res.end();
    });
});
/**
 * 获取指定猫咪的图片集
 * @param cid 猫咪ID
 * @param page 页码
 */
router.get("/cats/:cid/:page", um.middle_finder, um.middle_loadUser, (req, res) => {
    let p = (req.params || {});
    let cid = p.cid;
    let page = p.page;
    if (isNaN(cid) || isNaN(page)) return res.json(RES_CHECKER({ success: false, error: '参数有误' }));
    dm.getCatImgs(cid, page, (err, result) => {
        if (err) return res.json(RES_CHECKER({ success: false, error: err }));
        let data = [];
        let isCanSee2 = um.permissionCheck(true, req.user, 'see_private_cat_img');
        let hasImg = false;
        for (let index in result) {
            hasImg = true;
            let info = result[index];
            if (img_see1.has(info.ax) || (isCanSee2 && img_see2.has(info.ax))) {
                let uuid = NCUTCAT.tools.BufferToHex(info.q);
                if (uuid != '0x0') data.push({ hash: uuid, lore: info.u });
            }
        }
        res.json(RES_CHECKER({ success: true, result: data, has: hasImg }));
    });
});

/**
 * 获取指定UUID的图片
 * @param uuid 图片UUID
 */
router.get("/user", um.middle_finder, um.middle_loadUser, async (req, res) => {
    let uid = req.query.uid || (req.user || {}).uid;
    let name = "";
    if (!isNaN(uid)) {
        let result = await dm.getUserSketch(uid);
        if (result) {
            // if (result.sketch) {
            //     res.setHeader('Content-type', 'image/jpeg');
            //     req.query.ajax || res.write(result.sketch);
            //     return res.end();
            // } else 
            if (result.sketchIcon) {
                res.setHeader('Content-type', 'text/plain');
                res.write(result.sketchIcon);
                return res.end();
            }
        }
        let extra = req.query.uid ? await dm.getUserName(uid) : req.user;
        if (extra) {
            let reg = /[\u4E00-\u9FA5A-Za-z0-9]/;
            let scanner = text => {
                if (text)
                    for (let i = 0; i < text.length; i++)
                        if (reg.test(text[i])) return text[i].toUpperCase();
                return null;
            }
            name = extra.nick + extra.name + name;
        }
    }
    res.setHeader('Content-type', 'text/plain');
    res.write(name ? _userImgHelper(name) : 'def-user');
    return res.end();
});

function _userImgHelper(name) {
    let hex = crypto.createHash('md5').update(name).digest('hex').substring(0, 5);
    let index = parseInt('0x' + hex) % fm.icons.length;
    let icon = fm.icons[index];
    return icon.font_class;
}


//模块导出
module.exports = router;